package jdk8.lambda.lambda2;

import org.junit.Test;

import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 一、构造器引用
 *      和方法引用类似，函数式接口的抽象方法的形参和构造器的形参列表一致。
 *      抽象方法的返回值类型即为构造器所属的类的类型
 *
 * 二、数组引用
 *      把数组看作是一个特殊的类，则写法与构造器一致
 *
 *
 * Created by shkstart
 */
public class ConstructorRefTest {
	//构造器引用
    //Supplier中的T get()
    @Test
    public void test1(){
        Supplier<Employee> sup1 = new Supplier<Employee>() {
            @Override
            public Employee get() {
                return new Employee();
            }
        };

        Supplier<Employee> sup2 = () -> new Employee();

        Supplier<Employee> sup3 = Employee::new;

        System.out.println(sup1.get());
        System.out.println(sup2.get());
        System.out.println(sup3.get());
	}

	//Function中的R apply(T t)
    @Test
    public void test2(){
        Function<Integer, Employee> fun1 = new Function<Integer, Employee>() {
            @Override
            public Employee apply(Integer integer) {
                return new Employee(integer);
            }
        };
        System.out.println(fun1.apply(22));

        Function<Integer, Employee> fun2 = t -> new Employee(t);
        System.out.println(fun2.apply(23));

        Function<Integer, Employee> fun3 = Employee::new;
        System.out.println(fun3.apply(24));
	}

	//BiFunction中的R apply(T t,U u)
    @Test
    public void test3(){
        BiFunction<Integer, String, Employee> func1 = new BiFunction<Integer, String, Employee>() {
            @Override
            public Employee apply(Integer integer, String s) {
                return new Employee(integer, s);
            }
        };

        BiFunction<Integer, String, Employee> func2 = (i, s) -> new Employee(i, s);

        BiFunction<Integer, String, Employee> func3 = Employee::new;
        System.out.println(func3.apply(10, "Tom"));

	}

	//数组引用
    //Function中的R apply(T t)
    @Test
    public void test4(){

        Function<Integer, String[]> func1 = new Function<Integer, String[]>() {

            @Override
            public String[] apply(Integer integer) {
                return new String[integer];
            }
        };
        System.out.println(Arrays.toString(func1.apply(3)));

        Function<Integer, String[]> func2 = length -> new String[length];
        System.out.println(Arrays.toString(func2.apply(6)));

        Function<Integer, String[]> func3 = String[]::new;
        System.out.println(Arrays.toString(func3.apply(5)));
	}
}
